package org.liu.simpleTank.resource;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;

import org.liu.simpleTank.CONSTS;
import org.liu.simpleTank.Tank;

public class TankImage {
	private static int UNIT_SIZE = 28;
	private static BufferedImage enemy;
	private static BufferedImage player1;
	private static BufferedImage player2;
	private static BufferedImage shield;
	static {
		try {
			Class c = Class.forName("org.liu.simpleTank.resource.TankImage");
			URL enemyUrl = c.getResource("enemy.png");
			URL player1Url = c.getResource("player1.png");
			URL player2Url = c.getResource("player2.png");
			enemy = ImageIO.read(enemyUrl);
			player1 = ImageIO.read(player1Url);
			player2 = ImageIO.read(player2Url);
		} catch (Exception e) { e.printStackTrace(); }
	}
	
	private static int unitToSize(int unit) {
		return unit * UNIT_SIZE;
	}
	
	public static Image getRobotImg(Tank t, int frame) {
		int type = t.type;
		int dir = t.direction;
		int life = t.getLife();
		frame = frame % 2;
		int offX = 0;
		int offY = 0;
		
		if(type == CONSTS.TANK_1 || type == CONSTS.TANK_2) {
			offX = type == CONSTS.TANK_1 ? unitToSize(0) : unitToSize(4);
			offX += unitToSize(frame);
			offY = unitToSize(dir); // up: 0, right: 1, down: 2, left: 3
			return enemy.getSubimage(offX, offY, UNIT_SIZE, UNIT_SIZE);
		}

		if(type == CONSTS.TANK_3) {
			offY += unitToSize(4); // see picture enemy.png
			offX += unitToSize((3 - life) * 2); // TANK_3 has 3 life point 3 - life maps them to 0 1 2
			offX += unitToSize(frame);
			offY += unitToSize(dir);
			return enemy.getSubimage(offX, offY, UNIT_SIZE, UNIT_SIZE);
		}
		
		if(type == CONSTS.TANK_PLAYER1 || type == CONSTS.TANK_PLAYER2) {
			life = life > 4 ? 4 : life;
			offX += unitToSize((life - 1) * 2);
			offX += unitToSize(frame);
			offY += unitToSize(dir);
			if(type == CONSTS.TANK_PLAYER1)
				return player1.getSubimage(offX, offY, UNIT_SIZE, UNIT_SIZE);
			else
				return player2.getSubimage(offX, offY, UNIT_SIZE, UNIT_SIZE);
		}
		
		return null;
	}
}
